#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <signal.h>

/*次线程的个数*/
#define SECON_PTH_NUMS 	1

//线程参数结构体
typedef struct pth_arg{
	pthread_t tid;		/* 线程ID */
	int pthno;			/* 自定义的线程编号 */
}ptharg;

//全局变量结构体
struct global_var{
	int va;								/* 全局变量 */
	ptharg pthargs[SECON_PTH_NUMS];		/* 线程参数 */
	pthread_cond_t cond;				/* 条件变量 */
	pthread_mutex_t mutex;				/* 互斥锁*/
}glbva={.mutex = PTHREAD_MUTEX_INITIALIZER};


/*报错函数*/
void print_err(char *str, int line, int err_no)
{
	printf("%d,%s:%s",line,str,strerror(err_no));
	exit(-1);
}

/* 信号处理函数 */
void signal_fun(int signal)
{
	int ret = 0;
	
	/* 先删除互斥锁，再删除条件变量 */

	/* 删除线程互斥锁 */
	//ret= pthread_mutex_destroy(&glbva.mutex);
	if(ret != 0) print_err("pthread_mutex_destroy fail",__LINE__,ret);

	/* 删除线程条件变量 */
	//ret = pthread_cond_destroy(&glbva.cond);
	if(ret != 0) print_err("pthread_cond_destroy fail",__LINE__,ret);
	
	

	exit(0);//正常退出
}

/*线程函数*/
void * pth_fun(void *pth_arg)
{

	while(1)
	{
		pthread_mutex_lock(&glbva.mutex);
		pthread_cond_wait(&glbva.cond,&glbva.mutex);
		printf("glbva.va = %d\n",glbva.va);
		glbva.va = 0;
		pthread_mutex_unlock(&glbva.mutex);
		
	}
	return NULL;
} 

int main(void)
{
	int ret = 0;
	int i = 0;

	/* 线程条件变量初始化 */
	ret = pthread_cond_init(&glbva.cond,NULL);
	if(ret != 0) print_err("pthread_cond_inti fail",__LINE__,ret);

	/* 线程初始化 */
	for(i = 0;i < SECON_PTH_NUMS;i++)
	{
		ret = pthread_create(&glbva.pthargs[i].tid,NULL,pth_fun,NULL);
		if(ret !=0 ) print_err("pthread_create fail",__LINE__,ret);
	}

	signal(SIGINT,signal_fun);

	while(1)
	{
		pthread_mutex_lock(&glbva.mutex);
		glbva.va ++;
		if(glbva.va == 5)
		{
			ret = pthread_cond_signal(&glbva.cond);
			if(ret != 0) print_err("pthread_cond_signal fail",__LINE__,ret);
		}
		pthread_mutex_unlock(&glbva.mutex);
		/* sleep和互斥锁冲突，所有sleep放在外面 */
		sleep(1);

	}	
	
	return 0;
}






































